/**
 * 问题列表
 */
import query from '../../untils/mysql';
import { Tip } from '../../untils/untils';
import { check, validationResult } from 'express-validator';

const validator = [
    check('projectId').notEmpty().withMessage("项目id不能为空！")
]

const GET = async (req: any, res: any, next: any) => {
    try {
        var errors = validationResult(req);
        if (!errors.isEmpty()) {
            return Tip.tipError(res, errors.array()[0].msg);
        }

        const { userId } = req.auth;
        let { type = 2, projectId, pageSize = 10, pageIndex = 1 } = req.query;

        const commonsql = `select 
            a.*,
            b.name userName,
            b.name handlerName,
            b.name sendName,
            c.name projectName from problem a 
            left join user b on (a.user_id = b.id and a.handlerId = b.id and a.sendId = b.id ) 
            left join project c on a.project_id = c.id `

        let sql = commonsql + `where handlerId = '${userId}' and status = '2'`;
        switch (type) {
            //草稿
            case '1':
                sql = commonsql + `where user_id = '${userId}' and status = '1'`;
                break;
            // 我的待办
            case '2':
                sql = commonsql + `where handlerId = '${userId}' and status = '2'`;
                break;
            // 我的创建
            case '3':
                sql = commonsql + `where user_id = '${userId}' and status = '2'`;
                break;
            // 抄送给我
            case '4':
                sql = commonsql + `where sendId = '${userId}' and status = '2'`;
                break;
            // 活动问题
            case '5':
                sql = commonsql + `where status = '2' and actionStatus != '4'`;
                break;
            // 已解决
            case '6':
                sql = commonsql + `where status = '2' and actionStatus = '4'`;
                break;
            // 延期
            case '7':
                // sql = `select * from problem where status = '2' and actionStatus != '4' and endTime `;
                break;
            // 所有
            case '8':
                sql = commonsql + `where status = '2'`;
                break;
            default:
                break;
        }
        pageIndex = Number(pageIndex);
        pageSize = Number(pageSize);
        const offset = pageIndex*pageSize - pageSize;
        const sql1 = sql + ` and project_id = '${projectId}' limit ${pageSize} offset ${offset}`;
        const sql2 = sql + ` and project_id = '${projectId}'`;
        const data1 = await query(sql1);
        const data2 = await query(sql2);
        return Tip.tipSuccess(res, '查询成功', {
            data:data1,
            total:data2.length,
            pageIndex:pageIndex,
            pageSize:pageSize
        })
    } catch (error: any) {
        Tip.tipError500(res, error)
    }
}

export {
    GET,
    validator
}